<template>
  <div>
    <el-dialog :model-value="modelValue" title="修改新客户"
               width="800" @close="close">
      <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-position="top" label-width="auto">
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入"  suffix-icon="EditPen" />
        </el-form-item>
        <el-form-item label="账号" prop="account">
          <el-input v-model="formData.account" placeholder="请输入"
                    suffix-icon="EditPen" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="formData.password" type="password" placeholder="请输入"  suffix-icon="EditPen" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入"  suffix-icon="EditPen" />
        </el-form-item>
        <el-form-item label="地址" prop="">
          <el-input v-model="formData.address" :maxlength="250" placeholder="请输入" show-word-limit
                        type="textarea" />
        </el-form-item>
        <el-form-item label="余额" prop="money">
          <el-input-number v-model="formData.money" placeholder="请输入"  suffix-icon="EditPen" />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="formData.roleId" placeholder="请选择">
            <el-option v-for="item in roles" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avator">
          <el-upload
            ref="uploadRef"
            class="avatar-uploader"
            accept="image/*"
            :headers="headers"
            :action="imgUploadUrl"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
          <div  v-if="formData.avator" class="w-[60px] h-[60px]">
            <img :src="imgUrl + formData.avator" class="avatar" />
          </div>
          <el-icon v-else class="avatar-uploader-icon" size="80"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-switch v-model="formData.enabled"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">{{ "取消" }}</el-button>
          <el-button type="primary" @click="submit(ruleFormRef)">{{ "确定" }}</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { rules } from "./data";
import {ref, watch} from "vue";
import { ElMessage, FormInstance, UploadProps } from "element-plus";
import { imgUploadUrl, imgUrl } from "@/global";
import { useAppStore } from "@/store/app";
import { UpdateUser } from "@/api/user";
import {GetRoleList} from "@/api/roles.ts";
const emit = defineEmits(["update:modelValue", "init"]);
const appStore = useAppStore();
const uploadRef = ref<any>();
const headers = ref<any>({
  Authorization: 'Bearer ' + appStore.getToken
});
const props = defineProps<{
  modelValue: boolean;
  formData:any
}>();
const close = ():void => {
  uploadRef.value.clearFiles();
  emit("update:modelValue", false);
  emit("init");
};
const ruleFormRef = ref<FormInstance>();
const submit = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) return;
  await formEl.validate(async (valid: boolean) => {
    if (valid) {
      const res = await UpdateUser(props.formData)
      if(res.code == 200){
        ElMessage.success("修改成功")
        close();
      }else{
        ElMessage.error(res.message)
      }
    }
  });
};


const handleAvatarSuccess: UploadProps['onSuccess'] = (response,uploadFile) => {
  props.formData.avator = response.url
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
   if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('头像大小不可超过 2MB!')
    return false
  }
  return true
}

const roles = ref<any[]>([])
const getRoles = async () => {
  const res = await GetRoleList({
    isPage:false
  });
  if (res.code === 200) {
    roles.value = res.data;
  } else {
    roles.value = [];
  }
};
watch(
    () => props.modelValue,
    (newValue) => {
      if(newValue){
        getRoles()
      }
    }
)
</script>
